package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.*;
import com.example.demo.service.UserService;
import com.example.demo.utils.JsonTest;
import com.example.demo.utils.SendMail;
import com.example.demo.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.example.demo.utils.JsonTest.readJsonFile;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ApiResponse apiResponse;
    // params:  @RequestParam
    // data: + RequestBody
    // @PathVariable 路径里面传入id /insert/${id}

    public Boolean isHaveData(List list){
        return list.size()>0;
    }


    @GetMapping(value = "/getJson")
    public ApiResponse getJson(@RequestParam("jsonName") String jsonName){
        String path = JsonTest.class.getClassLoader().getResource(jsonName).getPath();
        JSONObject jobj = JSON.parseObject(readJsonFile(path));
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, jobj);
    }

    @PostMapping(value = "/uploadInfo")
    public ApiResponse uploadInfo(@RequestBody(required = false) User user){
        int flag = userService.uploadUserInfo(user);
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, flag);
    }

    @PostMapping(value = "/login")
    public ApiResponse login(@RequestBody(required = false) User user) {
        List<User> list = userService.selectUserIsLogin(user);
        User user1 = null;
        String message = StatusMessageMenu.SUCCESS;
        if (list.size() == 0) {
            message = StatusMessageMenu.LOGIN_FAILED;
        } else {
            user1 = list.get(0);
        }
        return new ApiResponse(StatusCodeMenu.SUCCESS, message, user1);
    }

    @GetMapping(value = "/getUserInfoByUsername")
    public ApiResponse getUserInfoByUsername(@RequestParam("info_username")String username){
        //登录后 肯定存在
        String message = StatusMessageMenu.SUCCESS;
        int code = StatusCodeMenu.SUCCESS;

        User user = new User();
        try {
            user = userService.selectUserIsExisted(username).get(0);
        }catch (IndexOutOfBoundsException e){
            message = StatusMessageMenu.NOT_FOUND;
            code = StatusCodeMenu.NOT_FOUND;
        }

        return new ApiResponse(code, message, user);
    }

    @GetMapping(value = "/findUserByUsername")
    public ApiResponse findUserByUsername(@RequestParam("username") String username){
        List<User> resultUserList = userService.selectUserIsExisted(username);
        boolean isExists = false;
        //如果该用户名已存在
        if(resultUserList.size() > 0){
            isExists = true;
        }
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, isExists);
    }

    @GetMapping(value = "/findUserByEmail")
    public ApiResponse findUserByEmail(@RequestParam("email") String email){
        List<User> resultUserList = userService.selectByEmail(email);
        boolean isExists = false;
        //如果该邮箱已存在
        if(resultUserList.size() > 0){
            isExists = true;
        }
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, isExists);
    }

    @PostMapping(value = "/regist")
    public ApiResponse regist(@RequestBody(required = false)RegistUserDto registUserDto){
        ApiResponse apiResponse = new ApiResponse();
        String backCode = registUserDto.getR_verifycode();
        String redisCode = (String) stringRedisTemplate.opsForHash().get("code", registUserDto.getR_username());
        boolean codeIsEquals = backCode.equals(redisCode);
        if(codeIsEquals == false){
            apiResponse.setCode(StatusCodeMenu.WRONG_SERVER);
            apiResponse.setData(codeIsEquals);
            apiResponse.setMessage(StatusMessageMenu.WRONG_VERIFY_CODE);
            return apiResponse;
        }

        User user = new User();
        user.setUsername(registUserDto.getR_username());
        user.setPassword(registUserDto.getR_passwordFir());
        user.setEmail(registUserDto.getR_email());
        int flag =  userService.addUser(user);

        if(flag == 0){
            apiResponse.setCode(StatusCodeMenu.WRONG_SERVER);
            apiResponse.setData(false);
            apiResponse.setMessage(StatusMessageMenu.REGIST_FAILED);
        }
        apiResponse.setCode(StatusCodeMenu.SUCCESS);
        apiResponse.setMessage(StatusMessageMenu.REGIST_SUCCESS);
        apiResponse.setData(true);
        return apiResponse;
    }

    /**
     * 首先生成将要发送给邮箱的验证码 然后保存在redis中
     * 等会注册按钮后 再从原位置中取*/

    @GetMapping(value = "/getCode")
    public ApiResponse sendVerifyCode(@RequestParam("email")String email,
                                      @RequestParam("username")String username){
        SendMail sendMail = new SendMail();
        String data = UuidUtil.getUuid(6);
        stringRedisTemplate.opsForHash().put("code", username, data);
        sendMail.sendMail(email, "恭喜您，账户验证成功！您当前验证码为： >"+ data +"<   ，其中有效时间为30分钟。若不是本人操作，请及时与网站管理员联系！@From.vincent.gitee.io");
        return new ApiResponse(StatusCodeMenu.SUCCESS, "尊敬的用户，您好！您的验证码信息已成功发送至邮箱，请注意查收！",  "");
    }

    @GetMapping(value = "/isExistsPhone/{phone}")
    public ApiResponse isExistsPhone(@PathVariable("phone")String phone,
                                     @RequestParam("username")String username) {
        List<User> list = userService.selectByPhone(phone);
        Boolean isExistsPhone = isHaveData(list);
        if(isExistsPhone == true){
            String name = list.get(0).getUsername();
            isExistsPhone = (!name.equals(username));  //注意不要用== 用equal才是仅仅从字符串是否相等来判断
        }
        //如果返回true 代表已经存在 并且不是本人
        return new ApiResponse(StatusCodeMenu.SUCCESS, StatusMessageMenu.SUCCESS, isExistsPhone);
    }
}
